<template>
  <div class="area-management">
    <div class="page-header">
      <div class="page-title" style="display: flex;align-items: center;gap: 16px;">
        区域管理
        <div class="filter-section">
          <el-input v-model="searchQuery" placeholder="搜索区域名称" clearable class="filter-item" @input="handleFilter">
          </el-input>
        </div>
      </div>
      <el-button type="primary" @click="handleAddArea">添加区域</el-button>
    </div>
    <el-row style="flex: 1; overflow: auto;" :gutter="16">
      <el-col :xs="24" :sm="24" :xl="12" v-for="area in filteredAreas" :key="area.id">
        <area-card :name="area.name + '(' + area.id + ')'" :water-meters="area.waterMeters"
          :electric-meters="area.electricMeters" :gas-meters="area.gasMeters">
          <!-- 定制标题栏操作按钮 -->
          <template #actions>
            <el-button size="small" type="primary" @click="handleEditArea(area)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteArea(area)">删除</el-button>
          </template>

          <!-- 定制左侧信息区域 -->
          <template #info>
            <el-form label-position="top" size="small" class="area-form">
              <el-form-item label="用水类型" class="form-item">
                <span>{{ area?.waterMeters.length > 0 ?
                  priceRuleStore.getPriceRuleNameById(area.waterMeters[0].price_rule_id) :
                  '暂无' }}</span>
              </el-form-item>

              <el-form-item label="用电类型" class="form-item">
                <span>{{ area?.electricMeters.length > 0 ?
                  priceRuleStore.getPriceRuleNameById(area.electricMeters[0].price_rule_id)
                  : '暂无'
                }}</span>
              </el-form-item>

              <el-form-item label="用气类型" class="form-item">
                <span>{{ area?.gasMeters.length > 0 ?
                  priceRuleStore.getPriceRuleNameById(area.gasMeters[0].price_rule_id)
                  : '暂无'
                }}</span>
              </el-form-item>
            </el-form>
          </template>
        </area-card>
      </el-col>
    </el-row>
  </div>
  <!-- 区域表单对话框组件 -->
  <area-form-dialog v-model="dialogVisible" :form-data="formData" :title="dialogTitle" @refresh="refreshData"
    @submit="handleFormSubmit" @close="handleFormClose" />
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useAreaStore } from '@/stores/area'
import { useCompanyStore } from '@/stores/company'
import { getMeterInfoApi } from '@/api/meter'
import { updateAreaApi, deleteAreaApi, createAreaApi } from '@/api/area'
import AreaFormDialog from './components/AreaFormDialog.vue'
import { usePriceRuleStore } from '@/stores/priceRule'
import AreaCard from '@/components/card/BlockCard.vue' // 导入新的卡片组件

const areaStore = useAreaStore()
const companyStore = useCompanyStore()
const priceRuleStore = usePriceRuleStore()
const processedAreas = ref([])

// 筛选相关
const searchQuery = ref('')

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref({
  id: null,
  name: ''
})

// 筛选后的区域列表
const filteredAreas = computed(() => {
  return processedAreas.value.filter(area => {
    const matchesSearch = !searchQuery.value || area.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    return matchesSearch
  })
})

// 处理筛选
function handleFilter() {
  // 筛选逻辑已通过计算属性 filteredAreas 实现
}

function mapMetersToAreas(areas, meters) {
  if (!Array.isArray(areas) || !Array.isArray(meters)) {
    throw new Error('areas 和 meters 参数必须是数组')
  }

  const METER_TYPES = {
    1: 'waterMeters',
    2: 'electricMeters',
    3: 'gasMeters'
  }

  return areas.map(area => {
    if (!('id' in area)) {
      throw new Error('区域对象必须包含 id 字段')
    }

    const initialMeterLists = {
      waterMeters: [],
      electricMeters: [],
      gasMeters: []
    }

    const areaMeters = meters.filter(meter => {
      if (!('area_id' in meter) || !('type' in meter)) {
        throw new Error('表计对象必须包含 area_id 和 type 字段')
      }
      return meter.area_id === area.id
    })

    areaMeters.forEach(meter => {
      const listName = METER_TYPES[meter.type]
      if (listName) {
        initialMeterLists[listName].push(meter)
      }
    })

    return {
      ...area,
      ...initialMeterLists
    }
  })
}

// 处理添加
function handleAddArea() {
  dialogTitle.value = '添加区域'
  formData.value = {
    id: null,
    name: ''
  }
  dialogVisible.value = true
}

// 处理编辑
function handleEditArea(area) {
  dialogTitle.value = '编辑区域'
  formData.value = {
    ...area,
  }
  dialogVisible.value = true
}

// 处理表单提交
async function handleFormSubmit(formData) {
  //检查有没有重复的名字
  if (areaStore.areas.some(item => item.name === formData.name && item.id !== formData.id)) {
    ElMessage.error('区域名称重复，请重新输入')
    return
  }
  try {
    if (formData.id) {
      await updateAreaApi(formData)
      ElMessage.success('更新成功')
    } else {
      await createAreaApi(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    refreshData()
  } catch (error) {
    ElMessage.error(`${formData.id ? '更新' : '创建'}失败：${error.message}`)
  }
}

// 刷新数据
async function refreshData() {
  await areaStore.fetchAreas()
  await processAreasData()
}

function handleFormClose() {
  dialogVisible.value = false
  formData.value = {
    id: null,
    name: ''
  }
}

// 处理删除
function handleDeleteArea(area) {
  ElMessageBox.confirm(
    `确定要删除区域 "${area.name}" 吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await deleteAreaApi('' + area.id)
        ElMessage.success('删除成功')
        refreshData()
      } catch (error) {
        ElMessage.error('删除失败：' + error.message)
      }
    })
    .catch(() => {
      // 用户点击取消，不做任何操作
    })
}

async function processAreasData() {
  const res = await getMeterInfoApi({
    company_id: companyStore.currentCompany.id,
  })
  processedAreas.value = mapMetersToAreas(areaStore.areas, res.data)
}

watch(() => companyStore.currentCompany, async () => {
  await processAreasData()
  await priceRuleStore.fetchPriceRuleList()
}, {
  immediate: true
})
</script>

<style>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  display: flex;
  gap: 16px;
}

.filter-item {
  width: 200px;
}

.area-form {
  height: 100%;
}

.form-item {
  flex: 1;
}

.form-item:last-child {
  margin-bottom: 0;
}
</style>